<?php

namespace App\Console\Commands;

use App\Models\DealLine;
use App\Models\EDealLog;
use App\Models\Recharge;
use App\Models\Wallet;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class UserProfit extends Command
{
    protected $signature = 'profit:sellprofit';

    protected $description = '用户算力产生的E格码';

    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        $start_time = date("Y-m-d", strtotime("-1 day"));

        $re_data = Recharge::whereDate('created_at', $start_time)->whereIn('type',['2','3'])->where(['status' => 2])->sum('money');
        
        $total_wallet = Wallet::all();
        $total_power = Wallet::sum('computing_power');
        $today_price = DealLine::orderBy('id', 'desc')->value('price');
        
        $total_tmc = bcdiv($re_data, $today_price, 8) * 0.45;
        
        // Log::channel('profit')->info('params:',[
        //     'total_power' => $total_power,
        //     'today_price' => $today_price,
        //     'total_tmc' => $total_tmc,
        // ]);

        DB::beginTransaction();
        try {
            $percent_100 = bcdiv(100, $total_power, 8);
            $change_tmc_100 = bcmul($total_tmc, $percent_100, 8);
            DealLine::orderBy('id', 'desc')->first()->update(['total_hand' => $change_tmc_100]);
            foreach ($total_wallet as $key => $value) {
                $percent = bcdiv($value->computing_power, $total_power, 8);
                $change_tmc = bcmul($total_tmc, $percent, 8);
                $value->tmc = $value->tmc + $change_tmc;
                $value->save();
                EDealLog::add_log($value->user_id, 0, $change_tmc, 1, '算力产生E格码',1);
            }
            DB::commit();
        } catch (\Exception $exception) {
            Log::channel('profit')->error('profit:UserProfit error', [
                'code' => $exception->getCode(),
                'message' => $exception->getMessage(),
            ]);
            DB::rollBack();
        }

    }
}
